/* Fonctions globales	*/

now = -> (new Date).getTime()

format = (ms) ->
	d = new Date (ms)
	twodigits(d.getMinutes()) + ':' +  twodigits(d.getSeconds())

twodigits = (v) ->
	if v < 10 then '0' + v else v
	
Array::unique = ->
  output = {}
  output[@[key]] = @[key] for key in [0...@length]
  value for key, value of output

playsound = (id) -> 
	$('#' + id)[0].play()

# Timer pomorodo

$.widget 'jt.pomodoro',

	options:
#	Temps d'une pomodoro
		pomodoro_time: 25*60
#	Temps de la courte pause
		break_time: 5*60
#	Temps de la longue pause
		long_break_time: 30*60
#	Autorise ou non le commencement d'une pomodoro
		allow_start: false

#	Constructeur
		
	_create: ->
	
		(@element.find '.progressbar').progressbar
			value: 0
			max: @options.pomodoro_time * 1000
			
		(@element.find '.begin').button
			text:false
			icons:
				primary: 'ui-icon-seek-start'
			disabled: true
		.click => 
			@_type = ''
			@_trigger 'aborted'
			@_end()
		
		(@element.find '.play').button
			text:false
			icons:
				primary: 'ui-icon-play'
			disabled: !@options.allow_start
		.click => @start_break()
		
		(@element.find '.stop').button
			text:false
			icons:
				primary: 'ui-icon-stop'
		.click => @long_break()
		
		@_interval = 0
		@_setcolor 'grey'
		
		

#	Rafraichissement des labels (dans la progressbar et dans le titre)

	_label : (time) ->
		(@element.find '.progress_label').text format time
		if @_type == 'pomo'
			($ 'title').text format time
		else 
			($ 'title').text '* ' + format time

#	Rafraichissement de la progressbar

	_refresh: ->
		(@element.find '.progressbar').progressbar
			value: (now() - @_last)
		@_label @_max - (now() - @_last)
		@_end() if @_max < (now() - @_last)

#	Appelé à la fin d'un intervalle
	
	_end: ->
		clearInterval @_interval;
		(@element.find '.progressbar').progressbar
			value: 0
		(@element.find '.play').button
			icons: primary: 'ui-icon-play'
		if @_type == 'pomo'
			@_trigger 'pomo_finished', null, 
				tags: (@element.find '.task').val()
			@short_break()		
		@_label 0
		($ '.stop').button 'enable'; @_enable_play()
		($ '.begin').button 'disable'

#	Définit la couleur de la progressbar

	_setcolor: (col) ->
		(@element.find '.ui-progressbar-value').css
			"background": col

#	Crée un nouvel intervalle et remet la progressbar à 0

	_setmax: (sec) ->
		clearInterval @_interval;		
		@_interval = setInterval (=> @_refresh()), 1000
		@_last = now()
		(@element.find '.progressbar').progressbar		
			max: sec * 1000
		@_max = sec * 1000
		(@element.find '.play').button
			icons: primary: 'ui-icon-play'
		@_refresh()
		if @_type == 'pomo' then (($ '.stop').button 'disable') else (($ '.stop').button 'enable')
		if @_type == 'long_break' then (($ '.play').button 'disable') else @_enable_play()
		($ '.begin').button 'enable'

#	Active le bouton play si c'est permis (cfr. options allow_start)

	_enable_play: ->
		(($ '.play').button 'enable') if @options.allow_start

#	Lors de l'appui sur le bouton play / pause

	start_break: ->
		if @_type == 'during_break'
			(@element.find '.play').button
				icons: primary: 'ui-icon-pause'
			@_last = now() - @_break_time
			@_interval = setInterval (=> @_refresh()), 1000
			@_type = 'pomo'
						
		else if @_type == 'pomo'
			(@element.find '.play').button
				icons: primary: 'ui-icon-play'
			@_type = 'during_break'
			clearInterval @_interval;
			@_break_time = (now() - @_last)
			
		else 
			@pomo()
			(@element.find '.play').button
				icons: primary: 'ui-icon-pause'

#	Appelé au début d'une pomodoro		

	pomo: ->
		@_type = 'pomo'
		@_setmax @options.pomodoro_time
		@_setcolor 'grey'
		@_trigger 'pomo_begin'
		
#	Appelé lors d'une "courte" pause à la fin d'une pomodoro
			
	short_break: ->
		@_type = 'short_break';
		@_setmax @options.break_time
		@_setcolor 'red'
		@_trigger 'break'
		
#	Appelé lors d'une longue pause	

	long_break: ->
		@_type = 'long_break';
		@_setmax @options.long_break_time
		@_setcolor '#8AE234'
		@_trigger 'long_break'
	
#	Autorise ou non le démarage d'une pomodoro
	
	_setOption: (k, v) ->
		(@element.find '.play').button disabled: !v if k == 'allow_start'
		@options[k] = v
			
	
# 	Barre de la tâche en cours

$.widget 'jt.task',
	options: 
		pomdoro: null
		log: null
		
	_create: ->
		@element.change =>
			@options.pomodoro.pomodoro 'option', 'allow_start': @element.val().replace(/^\s+|\s+$/g, "").length != 0
			@options.log.log 'refresh', @element.val()
			
	toggle_tag: (tag) ->
		tags = (@element.val().split ';')
		tags.push tag
		tags = (tag.replace(/^\s+|\s+$/g, "") for tag in tags).filter (x) -> 
			x.length != 0
		u = tags.unique()
		@element.val u.join ' ; '
		@element.change() if u.length == tags.length

	clear: ->
		old = @element.val()
		@element.val('') 
		@element.change() if old.replace(/^\s+|\s+$/g, "") != @element.val()

#	Affichage des journaux
	
$.widget 'jt.log',
	options: 
		task: null
		pomodoro: null
		clear_button: null
	_create: ->
		@refresh()
	refresh: (tags = '') ->
		@element.fadeOut(500).load 'log' , 
			tags: tags, =>
				@element.fadeIn(500).find('.tag').click  (a) =>
					@options.task.task 'toggle_tag', ($ a.target).text()

#	Initialisation
		
$ ->
	($ '#pomodoro_timer').pomodoro
		'pomo_finished': (event, data) =>
			$.post 'pomo',
				tags: ($ '.task').val(), (answer) => 
					($ '#log_container').log 'refresh'
					console.log answer
		'pomo_begin': -> playsound 'pomo_begin'
		'aborted': -> playsound 'aborted'
		'break': -> playsound 'break'
		'long_break': -> playsound 'long_break'
	
	($ '#pomodoro_timer').find('.task').task
		pomodoro: ($ '#pomodoro_timer')
		log: ($ '#log_container')
		
	($ '#log_container').log
		task: ($ '#pomodoro_timer').find('.task')
		pomodoro: ($ '#pomodoro_timer')
		
	($ '.clear').button
		text:false
		icons:
			primary: 'ui-icon-eject'
	.click -> 
		console.log	"($ '.task')", ($ '.task')
		($ '.task').task 'clear'
		

